// pages/phonedetail/phonedetail.js
const { phoneApi, versionApi, downloadApi } = require('../../utils/api');

Page({
  data: {
    phoneId: null,
    phoneInfo: null,
    versionList: [],
    regions: [
      { key: 'normal', name: '正式版', expanded: true },
      { key: 'international', name: '国际正式版', expanded: false },
      { key: 'eea', name: '欧洲EEA正式版', expanded: false },
      { key: 'russia', name: '俄罗斯正式版', expanded: false },
      { key: 'india', name: '印度正式版', expanded: false },
      { key: 'indonesia', name: '印尼正式版', expanded: false },
      { key: 'turkey', name: '土耳其正式版', expanded: false }
    ],
    regionVersions: {
      normal: [],
      international: [],
      eea: [],
      russia: [],
      india: [],
      indonesia: [],
      turkey: []
    },
    phoneImages: {
      1: '/images/mi10.png',
      2: '/images/mi10pro.png',
      3: '/images/mi10supreme.png',
      4: '/images/mi10s.png',
      5: '/images/mi11.png',
      6: '/images/mi11pro.png',
      7: '/images/mi11youth.png',
      8: '/images/mi11lite.png',
      9: '/images/mi11i.png',
      10: '/images/mi11i5g.png'
    },
    phoneList: [
      {
        id: 1,
        name: '小米 10',
        model: 'umi',
        firmwareCount: 8
      },
      {
        id: 2,
        name: '小米 10 Pro',
        model: 'cmi',
        firmwareCount: 8
      },
      {
        id: 3,
        name: '小米 10 至尊纪念版',
        model: 'cas',
        firmwareCount: 6
      },
      {
        id: 4,
        name: '小米 10S',
        model: 'thyme',
        firmwareCount: 4
      },
      {
        id: 5,
        name: '小米 11',
        model: 'venus',
        firmwareCount: 7
      },
      {
        id: 6,
        name: '小米 11 Pro / Ultra',
        model: 'star',
        firmwareCount: 5
      },
      {
        id: 7,
        name: '小米 11 青春活力版',
        model: 'lisa',
        firmwareCount: 3
      },
      {
        id: 8,
        name: '小米 11 Lite 5G NE',
        model: 'lisa',
        firmwareCount: 3
      },
      {
        id: 9,
        name: '小米 11i',
        model: 'haydn',
        firmwareCount: 4
      },
      {
        id: 10,
        name: '小米 11i 5G',
        model: 'pissarroin',
        firmwareCount: 4
      }
    ],
    showDownloadModal: false,
    currentVersion: null,
    downloadLinks: [],
    isCardFlash: false,
    isLoadingLinks: false
  },

  onLoad: function (options) {
    const phoneId = parseInt(options.id);
    this.setData({ phoneId });
    
    // 获取手机详情
    this.loadPhoneInfo(phoneId);
    
    // 获取版本列表
    this.loadVersionList(phoneId);
  },
  
  // 加载手机详情
  loadPhoneInfo: function(phoneId) {
    phoneApi.getPhoneDetail(phoneId).then(data => {
      this.setData({ phoneInfo: data });
    }).catch(err => {
      console.error('获取手机详情失败', err);
      wx.showToast({
        title: '获取设备信息失败',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    });
  },
  
  // 格式化日期
  formatDate: function(dateStr) {
    if (!dateStr) return '';
    
    // 处理包含YYYY的日期
    if (dateStr.includes('YYYY')) {
      const currentYear = new Date().getFullYear();
      return dateStr.replace('YYYY', currentYear);
    }
    
    try {
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return dateStr;
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    } catch (e) {
      console.error('日期格式化错误', e);
      return dateStr;
    }
  },
  
  // 加载固件版本列表
  loadVersionList: function(phoneId) {
    const params = {
      pageNum: 1,
      pageSize: 100,
      phoneId: phoneId
    };
    
    versionApi.getVersionList(params).then(data => {
      // 处理版本数据，按地区分类
      const versions = data.list || [];
      const regionVersions = {
        normal: [],
        international: [],
        eea: [],
        russia: [],
        india: [],
        indonesia: [],
        turkey: []
      };
      
      versions.forEach(version => {
        // 处理日期格式
        if (version.date && version.date.includes('YYYY')) {
          version.formattedDate = this.formatDate(version.date);
        } else {
          version.formattedDate = version.date;
        }
        
        const region = version.region || 'normal';
        if (regionVersions[region]) {
          regionVersions[region].push(version);
        } else {
          regionVersions.normal.push(version);
        }
      });
      
      this.setData({
        versionList: versions,
        regionVersions: regionVersions
      });
    }).catch(err => {
      console.error('获取版本列表失败', err);
    });
  },

  // 加载下载链接
  loadDownloadLinks: function(versionId, flashType) {
    this.setData({ isLoadingLinks: true });
    
    return downloadApi.getDownloadLinks(versionId).then(data => {
      // 根据 flashType 选择对应类型的链接
      const links = flashType === 'card' ? data.card : data.line;
      this.setData({
        downloadLinks: links || [],
        isLoadingLinks: false
      });
    }).catch(err => {
      console.error('获取下载链接失败', err);
      this.setData({ 
        isLoadingLinks: false,
        downloadLinks: []
      });
      wx.showToast({
        title: '获取下载链接失败',
        icon: 'none'
      });
    });
  },

  // 显示下载弹窗
  goToUpdateDetail: function(e) {
    const versionId = e.currentTarget.dataset.id;
    const version = this.data.versionList.find(v => v.id === versionId);
    const flashType = e.currentTarget.dataset.flashtype || 'card';
    
    if (version) {
      // 确保日期格式正确
      if (version.date && !version.formattedDate) {
        version.formattedDate = this.formatDate(version.date);
      }
      
      this.setData({
        showDownloadModal: true,
        currentVersion: version,
        isCardFlash: flashType === 'card',
        downloadLinks: []
      });
      
      // 加载下载链接
      this.loadDownloadLinks(versionId, flashType);
    }
  },

  // 切换地区版本展开状态
  toggleExpandVersion: function(e) {
    const type = e.currentTarget.dataset.type;
    const regions = this.data.regions.map(region => {
      if (region.key === type) {
        return { ...region, expanded: !region.expanded };
      }
      return region;
    });
    
    this.setData({ regions });
  },
  
  // 关闭下载弹窗
  closeDownloadModal: function() {
    this.setData({
      showDownloadModal: false,
      downloadLinks: [] // 清空下载链接
    });
  },
  
  // 处理下载链接点击
  handleDownloadLink: function(e) {
    const linkId = e.currentTarget.dataset.id;
    const link = this.data.downloadLinks.find(l => l.id === linkId);
    
    if (link) {
      // 复制链接到剪贴板
      wx.setClipboardData({
        data: link.url,
        success: () => {
          wx.showToast({
            title: '链接已复制',
            icon: 'success'
          });
          
          // 询问是否跳转到浏览器
          wx.showModal({
            title: '提示',
            content: '链接已复制，是否跳转到浏览器打开？',
            success: (res) => {
              if (res.confirm) {
                // 尝试打开浏览器（微信小程序内置浏览器）
                wx.openUrl ? wx.openUrl({
                  url: link.url,
                  success: () => {
                    console.log('成功打开浏览器');
                  },
                  fail: () => {
                    wx.showToast({
                      title: '无法打开浏览器，请手动粘贴链接',
                      icon: 'none'
                    });
                  }
                }) : wx.showToast({
                  title: '请手动打开浏览器粘贴链接',
                  icon: 'none'
                });
              }
            }
          });
        }
      });
    }
  }
}) 